import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

/**
 * 获取url上的query参数
 * @param {*} url
 * @returns
 */
function queryToJson(url) {
    if (!url) {
        url = window.location.href;
    }
    var query = url.substr(url.lastIndexOf('?') + 1),
        result = {},
        kv,
        key,
        value,
        item;
    if (query != url && query.indexOf('&') == -1) {
        query += '&';
    }
    query.split('&').forEach((param) => {
        if (param) {
            kv = param.split('=');
            key = kv[0];
            value = kv[1];
            item = result[key];
            if (typeof item === 'undefined') {
                result[key] = value;
            } else if (
                Object.prototype.toString.call(item) === '[object Array]'
            ) {
                item.push(value);
            } else {
                result[key] = [item, value];
            }
        }
    });
    return result;
}

/**
 * 深拷贝，如果只有一个参数，则默认第一个为数据源
 * @param {Object} target 
 * @param {Object} source 
 * @returns 
 */
 function deepCopy(target, source) {
    if (arguments.length == 1) {
        source = arguments[0];
        target = Array.isArray(source) ? [] : {};
    }
    if (!target) {
        throw Error('Cannot convert undefined or null to object');
    }
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            target[keys] = deepCopy(source[keys])
        } else {
            target[keys] = source[keys]
        }
    })
    return target;
}

// 学段年级文字展示
function grade2text(stageList = []){
    if (!stageList || stageList.length < 0) {
        return '';
    }
    let arr = [];
    stageList.forEach(element => {
        let gradeList =
            element.gradeList &&
            element.gradeList.map(subItem => subItem.gradeName);
        let name = `[${element.stageName}：${gradeList.join('，')}]`;
        arr.push(name);
    });
    return arr.join('； '); 
}
/**
 * 学段学科纯文字展示
 * @param {Array} stageList
 * @returns
 */
function fmtStageName(stageList = []) {
    if (!stageList || stageList.length < 0) {
        return '';
    }
    let arr = [];
    stageList.forEach(element => {
        let subjectArr =
            element.subjectList &&
            element.subjectList.map(subItem => subItem.subjectName);
        let name = `[${element.stageName}：${subjectArr.join('，')}]`;
        arr.push(name);
    });
    return arr.join('； ');
}
// 时间戳转格式化时间，time：时间戳，format：转换的时间格式字符串
function formatTimestamp(time, format){
    return dayjs(time).format(format)
}

const sizeFormat = function(fileSizeByte) {
    let numVal = 1;
    let unit = '';
    if (fileSizeByte < 1048576){
        numVal = fileSizeByte / 1024;
        unit = 'KB';
    } else if (fileSizeByte == 1048576) {
        unit = 'MB';
    } else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824){
        numVal = fileSizeByte / (1024 * 1024);
        unit = 'MB';
    } else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824){
        unit = 'GB';
    } else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776){
        numVal = fileSizeByte / (1024 * 1024 * 1024);
        unit = 'GB';
    } else if (fileSizeByte == 1099511627776) {
        unit = 'TB';
    } else {
        unit = 'TB+';
    }
    let newNum = ((numVal + '').indexOf('.') === -1) ? numVal: numVal.toFixed(2);
    return newNum + unit;
};

/**
 * 校验链接地址是否正确
 * @param { Object } rule 校验规则
 * @param { String } value 校验的值
 * @param { Function } callback 回调函数
 * @param { String } msg 校验失败的提示文字
 * @returns
 */

const validateUrl = (rule, value, callback, msg = '请输入正确的链接地址') => {
    let reg = /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;
    if ((rule.required && !value) || (value && !reg.test(value))) {
        callback(new Error(msg));
    }
    callback();
}

export {
    queryToJson,
    deepCopy,
    fmtStageName,
    formatTimestamp,
    sizeFormat,
    validateUrl,
    grade2text
};
